import React, { useState, useEffect } from 'react';
import { Card, Row, Col, Typography, Spin, Progress, Alert, Tag } from 'antd';
import { WarningOutlined, ShieldOutlined, TrendingUpOutlined } from '@ant-design/icons';

const { Title, Text } = Typography;

const RiskAnalysis = ({ symbol }) => {
  const [riskData, setRiskData] = useState(null);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    const fetchRiskData = async () => {
      try {
        const response = await fetch(`/api/stock/${symbol}/risk`);
        const data = await response.json();
        setRiskData(data);
      } catch (error) {
        console.error('获取风险数据失败:', error);
      } finally {
        setLoading(false);
      }
    };

    if (symbol) {
      fetchRiskData();
    }
  }, [symbol]);

  const getRiskLevel = (volatility) => {
    if (volatility < 20) return { level: '低风险', color: '#52c41a', score: 20 };
    if (volatility < 35) return { level: '中等风险', color: '#faad14', score: 50 };
    return { level: '高风险', color: '#f5222d', score: 80 };
  };

  const getSharpeRating = (sharpe) => {
    if (sharpe > 1.5) return { rating: '优秀', color: '#52c41a' };
    if (sharpe > 1.0) return { rating: '良好', color: '#faad14' };
    if (sharpe > 0.5) return { rating: '一般', color: '#f5222d' };
    return { rating: '较差', color: '#8c8c8c' };
  };

  if (loading) {
    return (
      <Card>
        <div className="loading-container">
          <Spin size="large" />
          <p>加载风险分析中...</p>
        </div>
      </Card>
    );
  }

  if (!riskData) {
    return (
      <Card>
        <div style={{ textAlign: 'center', padding: '50px' }}>
          <Text type="danger">无法获取风险数据</Text>
        </div>
      </Card>
    );
  }

  const riskLevel = getRiskLevel(riskData.volatility);
  const sharpeRating = getSharpeRating(riskData.sharpe_ratio);

  return (
    <div>
      <Title level={4}>风险评估分析</Title>

      {/* 风险概览 */}
      <Alert
        message={`风险等级: ${riskLevel.level}`}
        description={`该股票年化波动率为 ${riskData.volatility}%，属于${riskLevel.level}投资标的`}
        type={riskLevel.level === '低风险' ? 'success' : riskLevel.level === '中等风险' ? 'warning' : 'error'}
        showIcon
        style={{ marginBottom: '20px' }}
      />

      <Row gutter={[16, 16]}>
        <Col xs={24} md={12}>
          <Card title="风险指标" size="small">
            <Row gutter={[16, 16]}>
              <Col span={12}>
                <div className="metric-card">
                  <div className="metric-value risk-high">
                    {riskData.volatility}%
                  </div>
                  <div className="metric-label">年化波动率</div>
                  <Progress
                    percent={Math.min(riskData.volatility, 100)}
                    strokeColor={riskLevel.color}
                    showInfo={false}
                    size="small"
                  />
                  <Tag color={riskLevel.color}>{riskLevel.level}</Tag>
                </div>
              </Col>
              <Col span={12}>
                <div className="metric-card">
                  <div className="metric-value risk-high">
                    {riskData.max_drawdown}%
                  </div>
                  <div className="metric-label">最大回撤</div>
                  <Text type="secondary">历史最大跌幅</Text>
                </div>
              </Col>
            </Row>
          </Card>
        </Col>

        <Col xs={24} md={12}>
          <Card title="风险调整收益" size="small">
            <Row gutter={[16, 16]}>
              <Col span={12}>
                <div className="metric-card">
                  <div className="metric-value">
                    {riskData.sharpe_ratio}
                  </div>
                  <div className="metric-label">夏普比率</div>
                  <Tag color={sharpeRating.color}>{sharpeRating.rating}</Tag>
                </div>
              </Col>
              <Col span={12}>
                <div className="metric-card">
                  <div className="metric-value risk-medium">
                    {riskData.var_95}%
                  </div>
                  <div className="metric-label">VaR (95%)</div>
                  <Text type="secondary">单日最大可能损失</Text>
                </div>
              </Col>
            </Row>
          </Card>
        </Col>

        <Col xs={24} md={12}>
          <Card title="价格区间" size="small">
            <Row gutter={[16, 16]}>
              <Col span={8}>
                <div className="metric-card">
                  <div className="metric-value risk-low">
                    ${riskData.year_high}
                  </div>
                  <div className="metric-label">52周最高</div>
                </div>
              </Col>
              <Col span={8}>
                <div className="metric-card">
                  <div className="metric-value">
                    ${riskData.current_price}
                  </div>
                  <div className="metric-label">当前价格</div>
                </div>
              </Col>
              <Col span={8}>
                <div className="metric-card">
                  <div className="metric-value risk-high">
                    ${riskData.year_low}
                  </div>
                  <div className="metric-label">52周最低</div>
                </div>
              </Col>
            </Row>
          </Card>
        </Col>

        <Col xs={24} md={12}>
          <Card title="系统性风险" size="small">
            <div className="metric-card">
              <div className="metric-value">
                {riskData.beta?.toFixed(2) || '1.00'}
              </div>
              <div className="metric-label">Beta系数</div>
              <Text type="secondary">
                {riskData.beta > 1 ? '股票波动性大于市场' :
                 riskData.beta < 1 ? '股票波动性小于市场' :
                 '股票波动性与市场相同'}
              </Text>
            </div>
          </Card>
        </Col>
      </Row>

      <Card title="风险提示" style={{ marginTop: '20px' }} size="small">
        <Row gutter={[16, 8]}>
          <Col span={24}>
            <Alert
              message="投资风险提示"
              description={
                <div>
                  <p>• 过往表现不代表未来收益，投资有风险</p>
                  <p>• 建议根据个人风险承受能力做出投资决策</p>
                  <p>• 分散投资可以降低整体投资组合风险</p>
                  <p>• 定期审视投资组合，适时调整配置</p>
                </div>
              }
              type="info"
              showIcon
            />
          </Col>
        </Row>
      </Card>

      <Card title="指标说明" style={{ marginTop: '20px' }} size="small">
        <Row gutter={[16, 8]}>
          <Col span={12}>
            <Text strong>波动率:</Text> <Text>价格变动幅度，反映投资风险</Text>
          </Col>
          <Col span={12}>
            <Text strong>最大回撤:</Text> <Text>从最高点到最低点的最大跌幅</Text>
          </Col>
          <Col span={12}>
            <Text strong>夏普比率:</Text> <Text>风险调整后收益，越高越好</Text>
          </Col>
          <Col span={12}>
            <Text strong>VaR:</Text> <Text>在95%置信度下的最大可能损失</Text>
          </Col>
        </Row>
      </Card>
    </div>
  );
};

export default RiskAnalysis;
